from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from news.core.dtos.error import ErrorData
from news.core.exceptions import ValidationException
from news.core.models.image_processing import ImageTextGenerator
from news.core.serializers.image_processing import (
    ImageProcessingRequestSerializer,
    ImageProcessingResponseSerializer,
)


class ImageProcessingView(APIView):
    """
    post:
    图片内容生成API

    通过BLIP模型反推图片内容，调用LLM大语言模型翻译和润色后，
    随机插入图片，返回生成的图文信息

    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          properties:
            bucket_name:
              type: string
              description: MinIO存储桶名称
            image_name:
              type: string
              description: 图片文件名
    """

    serializer_class = ImageProcessingRequestSerializer

    def get_serializer_class(self):
        return self.serializer_class

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def post(self, request):
        try:
            # 验证输入数据
            serializer = ImageProcessingRequestSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)

            # 获取验证后的数据
            bucket_name = serializer.validated_data["bucket_name"]
            image_name = serializer.validated_data["image_name"]

            # 调用业务逻辑
            generator = ImageTextGenerator()
            result = generator.generate_content(bucket_name, image_name)

            # 序列化响应数据
            response_serializer = ImageProcessingResponseSerializer(data=result)
            response_serializer.is_valid(raise_exception=True)

            return Response(response_serializer.data, status=status.HTTP_200_OK)

        except ValidationException as e:
            return Response(
                ErrorData(status=e.code, error=e.message).to_dict(), status=e.code
            )
        except Exception as e:
            error_data = ErrorData(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR, error=str(e)
            )
            return Response(
                error_data.to_dict(), status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
